<?php

/**
 * Description of upload
 *
 * @author zhangyazhong By 2013-4-1 18:15:27
 * 
 * Info：上传类
 */
class framework_static_upload {

    private static $_maxSize = 10485760; //10MB
    private static $_savePath = "img"; //默认上传文件夹
    private static $_allowType = array();
    private static $_extEnsion = array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf');
    public $_error = ''; //错误信息

    /**
     * 取得上传文件的后缀
     * @access private
     * @param string $filename 文件名
     * @return boolean
     */

    private function getExt($filename) {
        $pathinfo = pathinfo($filename);
        return $pathinfo['extension'];
    }

    // 自动转换字符集 支持数组转换
    private function autoCharset($fContents, $from = 'gbk', $to = 'utf-8') {
        $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
        $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
        if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
            //如果编码相同或者非字符串标量则不转换
            return $fContents;
        }
        if (function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($fContents, $to, $from);
        } elseif (function_exists('iconv')) {
            return iconv($from, $to, $fContents);
        } else {
            return $fContents;
        }
    }

    /**
     * 检查上传的文件类型是否合法
     * @access private
     * @param string $type 数据
     * @return boolean
     */
    private function checkType($type) {
        if (!self::$_allowType) {
            return in_array(strtolower($type), self::$_allowType);
        }
        return true;
    }

    /**
     * 检查上传的文件后缀是否合法
     * @access private
     * @param string $ext 后缀名
     * @return boolean
     */
    private function checkExt($ext) {
        if (!self::$_extEnsion) {
            return in_array(strtolower($ext), self::$_extEnsion, true);
        }
        return true;
    }

    /**
     * 检查文件大小是否合法
     * @access private
     * @param integer $size 数据
     * @return boolean
     */
    private function checkSize($size) {
        if ($size > self::$_maxSize) {
            return FALSE;
        }
        return TRUE;
    }

    /**
     * 检查上传的文件
     * @access private
     * @param array $file 文件信息
     * @return boolean
     */
    private function check($file) {
        if ($file['error'] !== 0) {
            $this->_error = $file['error'];
            return FALSE;
        }
        //文件上传成功，进行自定义规则检查
        //检查文件大小
        if (!self::checkSize($file['size'])) {
            $this->_error = '上传文件大小不符';
            return FALSE;
        }
        //检查文件类型
        if (!self::checkExt($file['extension'])) {
            $this->_error = '上传文件类型不允许';
            return FALSE;
        }

        if (!is_uploaded_file($file['tmp_name'])) {
            $this->_error = '非法上传文件';
            return FALSE;
        }
        return true;
    }

    private function save($file) {
        $filename = $file['savepath'] . $file['savename'];
        // 如果是图像文件 检测文件格式
        if (in_array(strtolower($file['extension']), array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'))) {
            $info = getimagesize($file['tmp_name']);
            if (false === $info || ('gif' == strtolower($file['extension']) && empty($info['bits']))) {
                $this->_error = '非法图像文件';
                return FALSE;
            }
        }
        if (!move_uploaded_file($file['tmp_name'], self::autoCharset($filename, 'utf-8', 'gbk'))) {
            $this->_error = '文件上传保存错误！';
            return FALSE;
        }
        return TRUE;
    }

    public function uploadFileds($file, $savePath = '') {
        if (framework_static_common::str_empty($savePath)) {
            $savePath = PATH_WWW . '/files/upload/' . self::$_savePath . '/';
        } else {
            $savePath = PATH_WWW . "/files/upload/{$savePath}/";
        }
        if (!is_dir($savePath)) {
            if (!mkdir($savePath, 0777, true)) {
                $this->_error = '上传目录不存在';
                return FALSE;
            }
        } else {
            if (!is_writeable($savePath)) {
                $this->_error = '上传目录不可写';
                return FALSE;
            }
        }
        $fileArray = array();
        if (is_array($file['name'])) {
            $keys = array_keys($file);
            $count = count($file['name']);
            for ($i = 0; $i < $count; $i++) {
                foreach ($keys as $key) {
                    $fileArray[$i][$key] = $file[$key][$i];
                }
            }
        } else {
            $fileArray[] = $file;
        }
        $info = array();
        foreach ($fileArray as $key => $item) {
            if (!framework_static_common::str_empty($item['name'])) {
                $item['extension'] = self::getExt($item['name']);
                $item['savepath'] = $savePath;
                $item['savename'] = md5($item['name'] . time()) . "." . $item['extension'];
                if (!self::check($item)) {
                    return FALSE;
                }
                if (!self::save($item)) {
                    return FALSE;
                }
                unset($item['tmp_name'], $item['error']);
                $info[] = $item;
            }
        }
        return $info;
    }

}